package db

import (
	"admin/src/global"
	"admin/src/log"
	"admin/src/models"
	"fmt"

	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func InitDB() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		global.Config.Mysql.Username,
		global.Config.Mysql.Password,
		global.Config.Mysql.Host,
		global.Config.Mysql.Port,
		global.Config.Mysql.Database,
	)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Logger.Fatal("连接数据库失败", zap.Error(err))
	}

	log.Logger.Info("数据库连接成功")

	global.DB = db
	SynchronousDB(db)
}

// 同步数据库表结构
func SynchronousDB(db *gorm.DB) {
	db.AutoMigrate(
		&models.UserModel{},
		&models.RoleModel{},
		&models.MenuModel{},
		&models.RoleMenuModel{},
	)
}
